<template>
  <div class="space-category-analyze">
    <a-card title="图库分类占用">
      <v-chart
        :option="options"
        style="height: 320px; max-width: 100%"
        :loading="loading"
        autoresize/>
    </a-card>
  </div>
</template>
<script lang="ts" setup>
import VChart from 'vue-echarts'
import 'echarts'

import { computed, ref, watchEffect } from 'vue'
import { getSpaceCategoryAnalyzeUsingPost } from '@/api/spaceAnalyzeController.ts'
import { message } from 'ant-design-vue'

interface Props {
  queryAll?: boolean
  queryPublic?: boolean
  spaceId?: number
}

const props = withDefaults(defineProps<Props>(), {
  queryAll: false,
  queryPublic: false,
})
// 图表数据
const loading = ref(true)
const dataList = ref<API.SpaceCategoryAnalyzeResponse[]>([])

/**
 * 加载数据
 */
const fetchData = async () => {
  loading.value = true
  const res = await getSpaceCategoryAnalyzeUsingPost({
    queryAll: props.queryAll,
    queryPublic: props.queryPublic,
    spaceId: props.spaceId,
  })
  if (res.data.code === 0) {
    dataList.value = res.data.data ?? []
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

/**
 * 监听变量，改变时触发数据的重新加载
 */
watchEffect(() => {
  fetchData()
})
const options = computed(() => {
  const categories = dataList.value.map((item) => item.category)
  const countData = dataList.value.map((item) => item.count)
  const sizeData = dataList.value.map((item) => (item.totalSize / (1024 * 1024)).toFixed(2)) // 转为 MB

  return {
    tooltip: { trigger: 'axis' },
    legend: { data: ['图片数量', '图片总体积'], top: 'bottom' },
    xAxis: { type: 'category', data: categories },
    yAxis: [
      {
        type: 'value',
        name: '图片数量(张)',
        axisLine: { show: true, lineStyle: { color: '#254cad' } },
        axisLabel: { formatter: '{value} 张' } // 添加单位
      },
      {
        type: 'value',
        name: '图片总体积（MB）',
        position: 'right',
        axisLine: { show: true, lineStyle: { color: 'rgba(80,15,112,0.8)' } },
        axisLabel: { formatter: '{value} MB' }, // 添加单位
        splitLine: {
          lineStyle: {
            color: '#d7cb40',
            type: 'dashed',
          },
        },
      },
    ],
    series: [
      {
        name: '图片数量',
        type: 'bar',
        data: countData,
        yAxisIndex: 0,
        tooltip: {
          valueFormatter: value => value + ' 张'
        }
      },
      {
        name: '图片总体积',
        type: 'bar',
        data: sizeData,
        yAxisIndex: 1,
        tooltip: {
          valueFormatter: value => value + ' MB'
        }
      },
    ],
  }
})
</script>
<style scoped>

</style>
